package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexPatterns;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final StringRedisTemplate stringRedisTemplate;

    public UserServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.检验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.如果不符合，则返回错误信息
            return Result.fail("手机号格式错误");

        }

        //3.符合，则生成验证码
        String code = RandomUtil.randomNumbers(6);
        //存入redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.保存验证码到session
        session.setAttribute("code", code);
        //5.发送验证码
        log.debug("发送验证码：{}",code);
        //6.返回ok
        return Result.ok();

    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        String phone = loginForm.getPhone();
        //检验手机号格式是否正确（在这个项目登录不是重点所以就不检查手机号是否与验证码相匹配了，仅检查格式意思一下）
        if(RegexUtils.isPhoneInvalid(phone)){
            //2.如果不符合，则返回错误信息
            return Result.fail("手机号格式错误");

        }
        //2.验证验证码
      //  String cacheCode = session.getAttribute("code").toString();
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        String code = loginForm.getCode();
        if(cacheCode == null || !cacheCode.equals(code)){
            return Result.fail("验证码错误");
        }

        //3.根据手机号查询用户 select * from tb_user where phone = #{phone}
        User user = query().eq("phone", phone).one();
        //判断用户是否存在
        if(user == null){
            //不存在就创建
           user = creatUserWithPhone(phone);
        }
        //将user存入session
        //存入redis
        String token = null;


            //1.随机生成一个token
            token = UUID.randomUUID(true).toString();
            //2.将user转化为hash存储
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user,userDTO);
            Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                    CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fildName,fildValue)->
                            fildValue.toString()));
            //3.存储
            String tokenKey = LOGIN_USER_KEY+token;
            stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
            stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);

        //4.返回token
       // session.setAttribute("user", user);
        return Result.ok(token);
    }

    private User creatUserWithPhone(String phone) {
        //创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(6));

        save(user);
        return user;
    }
}
